<template>
  <div class="root-box" id="FortenList"
       v-loading="loading"
       element-loading-text="拼命加载中"
       element-loading-spinner="spinner-user"
       element-loading-background="rgba(0, 0, 0, 0)"
       element-loading-custom-class="spinner-custom"
  >

    <van-popup v-model="showmatrAction" position="right" class="popup-80" @opened="opened" v-if = "propFlagPopup" closeable  >
      <van-field class="scan"
                 ref="searchKey"
                 v-model="searchKey" :placeholder="'回车搜索' + strings.defaultString(propSearchTextAppend, '')"
                 left-icon="search"
                 size="large"
                 clearable
                 border
                 @keyup.enter.native="handlePageSearch"
                 @clear="onCancel"       style="width: 80%;"
      />
      <van-radio-group v-model="radioItem"   v-if="propIsRadio" @change="radioChange(null)" style="    max-height: 88%; overflow: auto "  remark="0">
        <van-cell-group >
          <van-cell
            style="border-top:0.5px solid  #ccc"
            v-for="(item) in (this.propFlagStatic && this.propFlagStatic == true ? getList() : list )"
            :key="item.id"
            currency=""
            @click="radioChange(item)"
          >
            <template #title>
              <slot :item="item">
                <van-row>
                  <van-col span="4">
                    <van-radio   :name="item" />
                  </van-col>
                  <van-col span="4">品名：</van-col>
                  <van-col span="14">{{item.matrName}}</van-col>
                </van-row>
                <van-row  >
                  <van-col span="4">
                  </van-col>
                  <van-col span="4">品规：</van-col>
                  <van-col span="14">{{item.matrSpec}}</van-col>
                </van-row>
              </slot>
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>


      <van-checkbox  v-if ="!propNoCheck && !propIsRadio && list.length > 0" @change="checkAll()" v-model  = "checkAllValue">全选</van-checkbox>
      <van-checkbox-group v-if="!propIsRadio" v-model="result" ref="checkboxGroup"  remark="1">
        <van-cell-group>
          <van-cell
            style="border-top:0.5px solid  #ccc"
            v-for="(item) in list"
            :key="item.id"
            currency=""
          >
            <template #title>
              <slot :item="item">
                <van-row>
                  <van-col span="2">
                    <van-checkbox :name="item" ref="checkboxes" shape="square" />
                  </van-col>
                  <van-col span="4">品名：</van-col>
                  <van-col span="18">{{item.matrName}}</van-col>
                </van-row>
                <van-row type="flex" justify="end">
                  <van-col span="22">品规：{{item.matrSpec}}</van-col>
                </van-row>
                <van-row type="flex" justify="end">
                  <van-col span="10">单位：{{item.requiredUnit}}</van-col>
                  <van-col span="12">数量：{{item.skuQtyApply}}</van-col>
                </van-row>
                <van-row type="flex" justify="end">
                  <van-col span="10" :style="{color: item.skuQtyStock == 0 ? 'red' : item.skuQtyStock < item.skuQtyApply ? 'Orange' : 'green'}">库存数量：{{item.skuQtyStock}}</van-col>
                  <van-col span="12">请领人：{{item.creator}}</van-col>
                </van-row>
                <van-row type="flex" justify="end">
                  <van-col span="22">请领时间：{{item.gmtApply}}</van-col>
                </van-row>
              </slot>
            </template>
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
      <van-row v-show = 'list.length > 0 && !propFlagNoPage'>
        <van-col span="18">
          <van-pagination class="page" @change="fetchData" v-model="tablePage.currentPage" :total-items="tablePage.totalResult" :items-per-page="tablePage.pageSize"   mode="simple">
          </van-pagination>
        </van-col>
        <van-col span="6">
          <van-popover
            v-model="showPopover"
            trigger="click"
            :actions="actions"
            @select="onSelect"
            placement="top"
            class="pagepop"
          >
            <template #reference>
              <van-button type="primary" size="small">每页{{tablePage.pageSize}}</van-button>
            </template>
          </van-popover>
        </van-col>
      </van-row>
      <van-row v-show = 'list.length < 1' style="text-align: center" >
        <van-col span="24">
          暂无
        </van-col>
      </van-row>
    </van-popup>
    <div v-else>
      <van-checkbox  v-if ="!propNoCheck && !propIsRadio && list.length > 0" @change="checkAll()" v-model  = "checkAllValue">全选</van-checkbox>
      <div style="    padding: 3px 10px;    background: #eee;" >
        <van-field class="scan"
                   ref="searchKey"
                   v-model="searchKey" :placeholder="'回车搜索' + strings.defaultString(propSearchTextAppend, '')"
                   left-icon="search"
                   size="large"
                   clearable
                   border
                   @keyup.enter.native="handlePageSearch"
                   @clear="onCancel"
        >
          <van-button v-if="utils.isVx()" slot="button" size="small" type="primary" @click="vxScan" style="background: none; border: 0px; padding: 0px;">
            <customImage :src="scanIcon" :width="20" :height="20"/>
          </van-button>

          <van-button v-if="cpFilterForm.length > 0" slot="button" size="small" type="primary" @click="$refs.customDrawerFilter.show()" style="background: none; border: 0px; padding: 0px 0px 0px 10px;">
            <customImage :src="filterIcon" :width="20" :height="20"/>
          </van-button>
        </van-field>
      </div>
      <div v-show = '!propFlagNoPage'  style="    width: 100%;  background: #fff;text-align: right; padding: 3px" >
        <van-popover
          v-model="showPopover"
          trigger="click"
          :actions="actions"
          @select="onSelect"
          placement="bottom"
          class="pagepop"
        >
          <template #reference>
            <van-button type="primary" size="small" style=" float: right;font-size: 11px;    padding: 1px 5px;height: 20px; ">每页{{tablePage.pageSize}}</van-button>
          </template>
        </van-popover>
        <span style=" font-size: 11px; float: right; line-height: 25px; margin-right: 10px;">
          <strong>总记录</strong>
          <span>{{tablePage.dataCount}}</span>
        </span>

        <van-pagination class="page"
                        @change="fetchData"
                        v-model="tablePage.currentPage"
                        :total-items="tablePage.totalResult"
                        :items-per-page="tablePage.pageSize"
                        style="float: right"
                        mode="simple" >
          <template #prev-text>
            <van-icon name="arrow-left" />
          </template>
          <template #next-text>
            <van-icon name="arrow" />
          </template>
        </van-pagination>
      </div>
      <div class="box-data" :style="getBoxDataStyle()" style=" max-height: calc(100vh - 90px); overflow: auto;    padding-bottom: 150px;width: 100%" @scroll="handleScroll">
        <van-checkbox-group v-if="!propIsRadio" v-model="result" ref="checkboxGroup" remark="2">
          <van-cell-group >
              <van-cell
                style="border-top:0.5px solid  #ccc"
                v-for="(item, index) in list"
                :key="item.id"
                currency=""
              >
                <template #title>
                  <slot :item="item" :index="index">
                    <van-collapse v-model="collapseList" :class="{'collapse-data': true,'collapse-data-label5': true == vanFieldLabelWith5}">

<!--                      顶部操作按钮-->
                      <customSpace fullWidth style="padding: 5px 0px;text-align: right; " v-if="cpBtnTopConfig.length > 0">
                        <template #content>
                          <customButton
                            v-for="rowButton in cpBtnTopConfig"
                            :key="rowButton.key"
                            :theme="utils.getTheme(rowButton.theme)"
                            :title="rowButton.title"
                            @click="btnTopCLick(rowButton,item)"
                          >
                          </customButton>
                        </template>
                      </customSpace>
                      <van-collapse-item :title="getShowLeft(item)" :name="item[cpShowFieldPk]">
                        <template #value >
                          <span v-html="getShowRight(item)"></span>
                        </template>
                        <van-row >
                          <van-col :span="column.span"  v-for="(column,index2) in cpShowFormItemList" :key="column.name + index2" :field="column.name">
                            <van-field
                              :value="item[column.name]"
                              :label="column.label"
                              :type="column.type"
                              :autosize="column.autosize"
                              readonly
                              @click="showItem(item)"
                              clickable
                            >
                              <template v-slot:input>
                                <div v-html="getItemValue(column,item)" style="    max-width: 58vw; overflow: auto; max-height: 200px; "></div>
                              </template>
                            </van-field>
                          </van-col>
                        </van-row>
                      </van-collapse-item>
                    </van-collapse>
                  </slot>
                </template>
              </van-cell>
          </van-cell-group>
        </van-checkbox-group>
        <van-row v-show = 'list.length < 1' style="text-align: center" >
          <van-col span="24">
            暂无
          </van-col>
        </van-row>
      </div>
    </div>

    <customDrawer
      title="筛选条件"
      subtitle="可回车搜索"
      ref="customDrawerFilter"
      :widthPx="300"
      :heightPx="291"
      :zIndex="1000"
      :autoHide="false"
      :footer="null"
    >
      <template #content>
        <customSpace fullWidth style="padding: 5px 0px;" >
          <template #content>
            <customButton  title="查询" theme="primary" size="small" @click="doFilter('query')"/>
            <customButton  title="清空" theme="warning" size="small" @click="doFilter('reset')"/>
            <customButton  title="关闭" theme="default" size="small" @click="doFilter('close')"/>
          </template>
        </customSpace>

        <div id="box-query" class="box-title">查询条件</div>
        <customForm :data="filterform" ref="filterformRef" style="padding-bottom: 10px; max-height: 50vh;overflow: auto" :layoutMini="false" @enter="doFilter('query')">
          <template #content>
            <customFormItem
              v-for="item in cpFilterForm"  :key="item.name"
              :parent="_self" :form="filterform" full-width
              :label="item.label" :name="item.name"  :type="item.queryType"
              :config="item.queryConfig"
            />
          </template>
        </customForm>

        <customForm  v-if="cpSortFieldList.length > 0" :data="filterform" ref="filterformRef2" style="padding-bottom: 10px;" :layoutMini="false" @enter="doFilter('query')">
          <template #content>
            <div id="box-sort" class="box-title">排序条件<small style="font-size: 11px;padding-left: 5px">字段、方式需同时指定</small></div>
            <customFormItem  :parent="_self" :form="filterform"  label="排序字段" name="sortField"  :type="constCommon.formItemType.selectStatic.name"
                             :config="{options: cpSortFieldList,label: 'label',value: 'name'}"
                             full-width
            />
            <customFormItem  :parent="_self" :form="filterform"  label="排序方式" name="sortType"  :type="constCommon.formItemType.selectStatic.name"
                             :config="{options: [{label:'降序', value: 'desc'},{label:'升序', value: 'asc'}]}"
                             full-width
            />
          </template>
        </customForm>
      </template>
    </customDrawer>

    <!--详情弹框-->
    <customDrawer  :title="cpDetailFormConfig.title" ref="customDrawerDetail" :autoHide="false" p94Only placement="right" :footer="null">
      <template #content>
        <customForm :data="detailform"   ref="editForm" :disabled="true" layoutMini>
          <template #content>
            <customFormItem
              v-for="item in cpDetailFormFieldList"  :key="item.name"
              :parent="_self" :form="detailform"
              :label="item.label" :name="item.name"  :type="item.queryType"
              :config="item.queryConfig"
              :full-width="24 == item.span"
            />
          </template>
        </customForm>
      </template>
    </customDrawer>
  </div>
</template>

<script>
/* eslint-disable*/
import { List, Pagination, Popover   } from 'vant'
import wx from 'weixin-js-sdk'
import customImage from '@/components/custom/form/customImage.vue'
export default {
  title: '分页list',
  name: 'DataList',
  components:{ customImage, List, Pagination, Popover },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      checkAllValue: false,
      result: [],
      tablePage: {
        currentPage: 1, // 当前页
        pageSize: 10, // 每页记录条数
        pageCount: 0, // 总页数
        totalResult: 0, //总分页数量
        dataCount: 0 //总记录数
      },
      queryWrapper: null, // 查询条件
      queryWrapperUser: null, // 查询条件
      showPopover: false,
      // 通过 actions 属性来定义菜单选项
      actions: [{ text: 10}, { text: 50}, { text: 100 }, { text: 200 }],
      searchKey: '',
      radioItem: '',
      showmatrAction: false,
      userParam: {},
      collapseList: [],
      scanIcon: require('@/assets/app/icon/scan.png'),
      filterIcon: require('@/assets/app/icon/filter.png'),
      filterform: {},
      detailform: {},
      scrllEnd: true
    };
  },
  props: [  'propAutoFetchData','propPageSize', 'propPreQueryWrapper'
    , 'propIsRadio', 'propFlagPopup', 'propUrl', 'propSearchFields'
    , 'propSearchTextAppend','propNoCheck','propFlagNoPage', 'propFlagStatic',
    'showFieldMain','showValueMain','showFieldList','showFieldPk','isOnlyShow', 'vanFieldLabelWith5', 'showDataFmtFun','filterForm'
    , 'sortDefault' , 'sortFieldList', 'detailFormConfig', 'propUserParam', 'btnTopConfig'
  ],
  methods: {
    checkAll() {
      this.$refs.checkboxGroup.toggleAll(this.checkAllValue);
    },
    //加载数据
    fetchData() {
      //静态数据
      if (this.propFlagStatic && this.propFlagStatic == true) {
        return
      }
      let queryConditions = []
      let orderConditions = []
      // 拼接初始条件
      if (this.propPreQueryWrapper) {
        queryConditions.push(...this.propPreQueryWrapper.queryConditions)
      }

      if (this.queryWrapper != null && this.queryWrapper ) {
        queryConditions.push(...this.queryWrapper.queryConditions)
      }

      if (this.queryWrapperUser != null && this.queryWrapperUser ) {
        queryConditions.push(...this.queryWrapperUser.queryConditions)
      }

      let sortWrapper = this.$newWrapper()
      // 自定义排序
      if (this.filterform && this.filterform.sortField && this.filterform.sortType) {
        sortWrapper.orderBy(this.filterform.sortType,this.filterform.sortField)
      } else if (this.sortDefault) { // 默认排序
        sortWrapper.orderBy(this.sortDefault.type,this.sortDefault.field)
      } else {
        if (this.queryWrapper && this.queryWrapper.orderConditions) orderConditions = this.queryWrapper.orderConditions
        if (this.queryWrapperUser && this.queryWrapperUser.orderConditions) orderConditions.push(...this.queryWrapperUser.orderConditions)
      }
      if (sortWrapper.orderConditions) {
        orderConditions.push(...sortWrapper.orderConditions)
      }

      let url = '/dept/apply_auto/page'
      if (this.propUrl)  url = this.propUrl
      this.list = []

      const params = {
        queryString: JSON.stringify(queryConditions),
        orderString: JSON.stringify(orderConditions),
        currentPage: this.tablePage.currentPage,
        rowsPerPage: this.tablePage.pageSize,
        userParam: this.userParam
      }

      if (this.propUserParam) {
        if (!params.userParam) {
          params.userParam = {}
        }
        Object.keys(this.propUserParam).forEach(key => {
          params.userParam[key] = this.propUserParam[key]
        })
      }
      this.collapseList = []
      // this.utilVue.loadShow(true)
      this.loading = true
      this.$ajax.get(url, {params}).then(response => {
        // this.utilVue.loadHide()
        if (response.code == 0) {
          this.tablePage.dataCount = response.count
          this.tablePage.totalResult = parseInt(response.count == null ? response.data.length : response.count, 10)
          this.tablePage.pageCount = Math.ceil(this.tablePage.dataCount / this.tablePage.pageSize)

          if (response.data.length > 0) {
            if (this.showDataFmtFun) {
              this.list = this.showDataFmtFun(response.data)
            } else {
              this.list = response.data
            }

            this.collapseList = this.list.map(tmp => {
              return tmp[this.cpShowFieldPk]
            })
            this.$emit('afterLoad',this.list)
          } else {
            // this.$notify.success('暂无数据')
          }
        }
        this.loading = false;
      }).catch(err => {
        this.loading = false;
      })
    },

    //添加数据
    pushData(data, isAppend = false) {
      if (isAppend) {
        this.list.push(data)
      } else{
        this.list = data
      }

      this.collapseList = this.list.map(tmp => {
        return tmp[this.cpShowFieldPk]
      })
    },

    //设置查询条件
    setQueryWrapper(wrapper, autoReload = true) {
      this.queryWrapper = wrapper
      if (autoReload) {
        this.fetchData()
      }
    },

    //获取已选中的
    getChecks() {
      return this.result
    },
    onSelect(action) {
      this.tablePage.pageSize = action.text
      this.fetchData()
    },
    showItem(item) {
      if (this.cpDetailFormEnabled) {
        this.detailform = JSON.parse(JSON.stringify(item))
        this.detailFormShow()
        return
      }
      if (true == this.isOnlyShow) {
        return
      }
      setTimeout(() => {
        this._showItem(item)
      }, 500)
    },
    _showItem(item) {
      if (item != null) {
        this.$emit('click', item)
      } else {
        this.$emit('click', this.radioItem)
      }
      this.close()
    },
    radioChange(item) {
      if (item != null) {
        console.log('FortenList.radioChange', item)
        this.$emit('change', item)
      } else {
        console.log('FortenList.radioChange', item)
        this.$emit('change', this.radioItem)
      }
      this.close()
    },
    opened() {
      this.fetchData()
      setTimeout(() => {
        this.$refs.searchKey.focus()
      }, 1000)
    },
    show(){
      this.showmatrAction = true
    },
    close(){
      this.showmatrAction = false
    },
    //全局搜索
    handlePageSearch() {
      this.queryWrapperUser = this.$newWrapper()
      this.propSearchFields.forEach(field => this.queryWrapperUser.orlike(field, this.searchKey))
      this.fetchData()
    },
    //全局搜索
    onCancel() {
      this.searchKey = ''
      this.queryWrapperUser = null
      this.fetchData()
    },
    //全局搜索
    setUserParam(userParam2) {
      this.userParam = userParam2
    },

    getList() {
      //静态数据
      if (this.propFlagStatic && this.propFlagStatic == true) {
        if (this.strings.isNotBlank(this.searchKey)) {
          return  this.list.filter(ob => ob.text.indexOf(this.searchKey) > -1
            || this.pyutils.getAllFirstLetter(ob.text).toLowerCase().indexOf(this.searchKey.toLowerCase()) > -1
            || this.pyutils.chineseToPinYin(ob.text).toLowerCase().indexOf(this.searchKey.toLowerCase()) > -1)
        }
        return this.list
      }
      this.list
    },
    getBoxDataStyle() {
      // let style= {}
      // style.overflow = 'auto'
      // style.maxHeight = (window.clientHeight - 150) + 'px'
      // console.log('window.innerHeight', window.innerHeight)
      // console.log('window.clientHeight', document.documentElement.clientHeight)
      return {}
    },

    //左侧标题
    getShowLeft(data) {
      let findList = this.cpShowFieldList.filter(item => true == item.isTitle)
      if (findList == null || findList.length == 0) {
        return ''
      }

      let msgList = []
      let msgOne
      let value
      findList.forEach(item => {
        msgOne = ''
        value = data[item.name]
        if (item.fmtFun) {
          msgOne = item.fmtFun(data[item.name], data)
        } else if (item.queryConfig && item.queryConfig.dictType) {
          // bool类型需要转换下
          if (item.flagBoolean !=undefined && true == item.flagBoolean){
            if ([true,1,'true','1'].includes(data[item.name])) {
              msgOne = this.utils.getDictLabel('1', item.queryConfig.dictType, '')
            }else{
              msgOne = this.utils.getDictLabel('0', item.queryConfig.dictType, '')
            }
          }else {
            msgOne = this.utils.getDictLabel(data[item.name], item.queryConfig.dictType, '')
          }
        } else  if (this.constCommon.formItemType.selectStatic.name == item.queryType) {
          let findIndex =  item.queryConfig.options.findIndex(item => item.value == value)
          if (findIndex != -1) {
            msgOne = item.queryConfig.options[findIndex].label
          }
        } else {
          msgOne = data[item.name]
        }
        if (item.isTitleWithLabel) {
          msgOne = item.label + ":" + msgOne
        }
        msgList.push(msgOne)
      })
      return msgList.join('')
    },

    //右侧标题
    getShowRight(data) {
      if (this.cpTitleSubField == null) {
        return ''
      }

      let msgList = []
      let msgOne
      this.cpTitleSubField.forEach(item => {
        msgOne = ''
        if (item.fmtFun) {
          msgOne = item.fmtFun(data[item.name], data)
        } else if (item.queryConfig && item.queryConfig.dictType) {
          // bool类型需要转换下
          if (item.flagBoolean !=undefined && true == item.flagBoolean){
            if ([true,1,'true','1'].includes(data[item.name])) {
              msgOne = this.utils.getDictLabel('1', item.queryConfig.dictType, '')
            }else{
              msgOne = this.utils.getDictLabel('0', item.queryConfig.dictType, '')
            }
          }else {
            msgOne = this.utils.getDictLabel(data[item.name], item.queryConfig.dictType, '')
          }
        } else {
          msgOne = data[item.name]
        }
        if (item.isTitleSubWithLabel) {
          msgOne = item.label + ":" + msgOne
        }
        msgList.push(msgOne)
      })
      return msgList.join('')
    },

    // 微信扫描
    vxScan() {
      let that = this
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          try {
            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
            if (result && result.split(',').length  == 2) {
              that.searchKey = result.split(',')[1]
              that.handlePageSearch()
            }
          }catch (e) {
            alert('扫描处理异常异常' + e)
          }
        }
      })
    },
    doFilter(type) {
      switch (type){
        case 'query': {
          this.filterQuery()
          break
        }
        case 'reset': {
          this.filterform = {}
          if (this.sortDefault) { // 默认排序
            this.$set(this.filterform, 'sortType',this.sortDefault.type)
            this.$set(this.filterform, 'sortField',this.sortDefault.field)
            this.utilMessage.info(`排序条件已重置为默认规则`)
          }
          break
        }
        case 'close': {
          this.$refs.customDrawerFilter.hide()
          break
        }
      }
    },

    // 搜索确认
    filterQuery() {
      this.$refs.customDrawerFilter.hide()
      let value
      let itemConfig
      let queryWrapperUser = this.$newWrapper()
      // 查询条件
      let fieldName
      this.cpFilterForm.forEach(itemConfig => {
        fieldName = itemConfig.name
        value = this.filterform[fieldName]
        let itemType = this.strings.defaultString(itemConfig.queryType, this.constCommon.formItemType.inputText.name)

        // 自定义日期区间，特殊处理
        if (itemType == this.constCommon.formItemType.datePickerBetween.name) {
          let dateStart = this.filterform[fieldName + 'Start']
          let dateEnd = this.filterform[fieldName + 'End']
          if (this.strings.isBlank(dateStart) && this.strings.isBlank(dateEnd)) {
            return true
          }

          dateStart = this.strings.defaultString(dateStart, '1970-01-01')
          dateEnd = this.strings.defaultString(dateEnd, '2099-12-12')

          if (dateStart.indexOf(':') == -1) {
            dateStart += ' 00:00:00'
          }
          if (dateEnd.indexOf(':') == -1) {
            dateEnd += ' 23:59:59'
          }
          queryWrapperUser.between(fieldName,[dateStart,dateEnd])
          return true
        }

        if (![undefined, null].includes(value)) {
          switch (itemType) {
            case this.constCommon.formItemType.inputText.name: {
              queryWrapperUser.orlike(fieldName, this.strings.trim(value))
              break
            }
            case this.constCommon.formItemType.datePicker.name: {
              let datePattern = 'yyyy-MM-dd'
              let value1 = this.dates.toDate(value, datePattern) + '  00:00:00'
              let value2 = this.dates.toDate(value, datePattern) + '  23:59:59'
              queryWrapperUser.between(fieldName,[value1,value2])
              break
            }
            case this.constCommon.formItemType.selectStatic.name: {
              // 多选
              if (true == itemConfig.queryConfig.multiple) {
                queryWrapperUser.in(fieldName, value)
              } else {
                queryWrapperUser.eq(fieldName, value)
              }
              break
            }
            case this.constCommon.formItemType.selectDict.name: {
              // 多选
              if (true == itemConfig.queryConfig.multiple) {
                queryWrapperUser.in(fieldName, value)
              } else {
                queryWrapperUser.eq(fieldName, value)
              }
              break
            }
            case this.constCommon.formItemType.switch.name: {
              queryWrapperUser.eq(fieldName, value)
              break
            }
            default: {
              throw Error(`暂不支持筛选，类型: ${fieldName}`)
            }
          }
        }
      })
      // if (this.filterform && this.filterform.sortField && this.filterform.sortType) {
      //   queryWrapperUser.orderBy(this.filterform.sortType,this.filterform.sortField)
      // }
      this.queryWrapperUser = queryWrapperUser
      this.fetchData()
    },

    // 列内容
    getItemValue(column,item) {
      let value = item[column.name]
      // bool类型需要转换下
      if (column.flagBoolean !=undefined && true == column.flagBoolean){
        if ([true,1,'true','1'].includes(value)) {
          return this.utils.getDictLabel('1', column.queryConfig.dictType, '')
        }else{
          return this.utils.getDictLabel('0', column.queryConfig.dictType, '')
        }
      }
      // 数据字典
      if (this.constCommon.formItemType.selectDict.name == column.queryType) {
        return this.utils.getDictLabel(value, column.queryConfig.dictType,value , true)
      } else  if (this.constCommon.formItemType.selectStatic.name == column.queryType) {
        let findIndex =  column.queryConfig.options.findIndex(item => item.value == value)
        if (findIndex != -1) {
          value = column.queryConfig.options[findIndex].label
        }
      }
      return this.strings.defaultString(value,'')
    },

    // 详情弹框显示
    detailFormShow() {
      this.$refs.customDrawerDetail.show()
    },

    // 详情弹框隐藏
    detailFormHide() {
      this.$refs.customDrawerDetail.hide()
    },

    // 顶部操作按钮点击
    btnTopCLick(btnConfig, dataRow) {
      // 包含请求地址，直接调用
      if (btnConfig.actionAddr) {
        let actionAddr = btnConfig.actionAddr
        actionAddr = this.strings.replaceAll(actionAddr,'{id}',dataRow.id)
        let confirmMsg = `确认执行${btnConfig.title}操作?`
        if (btnConfig.confirmMsgFun) {
          confirmMsg = btnConfig.confirmMsgFun(dataRow)
        }
        this.utilMessage.confirm(confirmMsg, () => {
          if (btnConfig.actionType == 'get') {
            this.utilVue.loadShow(true)
            this.$ajax.get(actionAddr).then(resp => {
              this.utilVue.loadHide()
              if(resp.success) {
                this.utilMessage.success(resp.msg)
              }
            })
          }else if (btnConfig.actionType == 'post') {
            this.utilVue.loadShow(true)
            this.$ajax.post(actionAddr, btnConfig.withData ? dataRow : {}).then(resp => {
              this.utilVue.loadHide()
              if(resp.success) {
                this.utilMessage.success(resp.msg)
              }
            })
          }else {
            this.utilMessage.warning(`暂不支持操作 ${btnConfig.actionType}`)
          }
        })
        return
      }
    },

    handleScroll(e) {
      const {scrollTop, clientHeight, scrollHeight} = e.target
      if (!this.scrllEnd) {
        return
      }

      let toPage = -1
      // 滚动到底部
      if ((scrollTop + clientHeight + 10) >= scrollHeight){
        if (this.tablePage.currentPage < this.tablePage.pageCount) {
          toPage = this.tablePage.currentPage + 1
        }
      }
      // 滚动到顶部
      if (scrollTop == 0) {
        if (this.tablePage.currentPage > 1 &&  this.tablePage.pageCount > 1) {
          toPage = this.tablePage.currentPage - 1
        }
      }
      if (toPage != -1) {
        this.scrllEnd = false
        this.tablePage.currentPage = toPage
        this.fetchData()
        setTimeout(() => {
          this.scrllEnd = true
        }, 1000)
      }
    }
  },
  created() {
    if (this.propAutoFetchData && this.propAutoFetchData == true)  this.fetchData()
  },
  computed: {
    cpShowFieldPk() {
      if (!this.showFieldPk) {
        return 'id'
      }
      return  this.showFieldPk
    },
    cpTitleSubField() {
      let findList = this.cpShowFieldList.filter(item => true == item.isTitleSub)
      if (findList && findList.length > 0 ) {
        return findList
      }
      return  null
    },

    //显示字段
    cpShowFieldList() {
      if (!this.showFieldList) {
        return []
      }
      return this.showFieldList.filter(item1 => !item1.showAllDisabled)
    },

    // 内容表单显示字段
    cpShowFormItemList() {
      return this.cpShowFieldList.filter(item1 => !item1.showDisabled && !item1.isTitle && !item1.isTitleSub && !item1.showFormDtlDisabled)
    },

    //查询字段
    cpFilterForm() {
      let fieldList = this.cpShowFieldList.filter(item1 => !item1.filterDisabled)
      let index = 1
      // 默认顺序字段
      let orderDefault = {
        busDate: -490,
        busKey: -480,
        hospitalId: -390,
        supplierId: -380,
      }
      fieldList.forEach(item => {
        if (item.filterOrder == undefined) {
          if (orderDefault[item.name] != undefined) {
            item.filterOrder = orderDefault[item.name]
          } else{
            item.filterOrder = index
          }
          index++
        }
      })
      fieldList = fieldList.sort((o1, o2) => {
        return o1.filterOrder - o2.filterOrder
      })
      return fieldList
    },

    // 排序字段
    cpSortFieldList() {
      return this.cpShowFieldList.filter(item1 => !item1.sortDisabled)
    },

    // 详情表单字段
    cpDetailFormFieldList() {
      return this.cpShowFieldList.filter(item1 => !item1.showFormOpenDisabled)
    },

    // 详情表单配置
    cpDetailFormConfig() {
      let config = this.detailFormConfig || {}
      let configAll = {
        enabled: false,
        title: '详情',
      }
      Object.keys(configAll).forEach(key => {
        if (config[key] == undefined) {
          config[key] = configAll[key]
        }
      })
      return config
    },

    // 详情表单是否可用
    cpDetailFormEnabled() {
      return this.cpDetailFormConfig.enabled
    },

    // 顶部操作按钮配置
    cpBtnTopConfig() {
      return this.btnTopConfig || []
    }
  },
  mounted() {
    if (this.sortDefault) {
      this.$set(this.filterform, 'sortType',this.sortDefault.type)
      this.$set(this.filterform, 'sortField',this.sortDefault.field)
    }
  }
}
</script>

<style scoped lang="scss">
  .root-box{
    margin-bottom: 66px;
    background-color: #fff;

    .van-button{
      height: 25px;
    }

    .page /deep/ li{
      height: 25px;
    }
  }

  .collapse-data{
    /deep/ .van-col{
      display: inline-block !important;
      float: none !important;
    }

    /deep/ .van-field,/deep/ .van-cell{
      padding: 1px 3px !important;
    }
    /deep/ .van-collapse-item__title{
      border-bottom: 1px #000 solid !important;

      .van-cell__title{
        font-weight: bold;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 13px;
        max-width: calc(100vw - 50px);
      }
    }
    /deep/ .van-field__control,/deep/ .van-field__label{
      font-size: 12px !important;
    }
    /deep/ .van-field__label{
      width: 3em !important;
    }
  }

  .collapse-data-label5{
    /deep/ .van-field__label{
      width:5em !important;
    }
  }

  .scan /deep/ .van-field__control::placeholder{
    color: #000 !important;
    font-size: 11px !important;
    font-style: italic !important;
  }

  .scan /deep/ .van-field__control:focus{
    border: 1px #409eff solid !important;
  }

  .scan /deep/ .van-field__control{
    border: 1px #eee solid !important;
  }

  .scan{
    border-radius: 10px;
  }
  .scan /deep/ .van-field__left-icon{
    margin-top: 3px !important;
  }

  .box-data /deep/ .van-collapse-item__title .van-cell__value{
    position: absolute;
    right: 22px;
    font-size: 12px;
  }
</style>
